package com.boot.springboot.component.qrcode.controller;

import cn.hutool.extra.qrcode.QrCodeUtil;
import com.boot.springboot.component.qrcode.service.SUserTokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *  二维码扫码登陆练习
 *
 * @author luowenjie
 * @since 2021/11/23 19:29
 */
@Controller
@RequestMapping("/qrcode")
@Slf4j
@Api(tags = "临时二维码接口模块")
public class QrCodeController {

    @Autowired
    SUserTokenService sUserTokenService;

    @RequestMapping(value = "/getLoginQr" ,method = RequestMethod.GET)
    @ApiOperation(value = "获取登录二维码、放入Token")
    @ResponseBody
    public void createCodeImg(HttpServletRequest request, HttpServletResponse response){
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");

        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        try {
            //这里没啥操作 就是生成一个UUID插入 数据库的表里
            String uuid = sUserTokenService.createQrImg();
            response.setHeader("uuid", uuid);
            // 这里是开源工具类 hutool里的QrCodeUtil
            // 网址：https://hutool.cn/docs/#/
            QrCodeUtil.generate(uuid, 300, 300, "jpg",response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/lgoin")
    @ApiOperation(value = "跳转到前端扫码页面")
    public ModelAndView qrCode() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("qrCode");
        modelAndView.addObject("url", 12345);
        return modelAndView;
    }

    @GetMapping("/loginSuccess")
    @ApiOperation(value = "跳转到登陆成功页面")
    public ModelAndView loginSuccess() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("loginSuccess");
        modelAndView.addObject("url", 12345);
        return modelAndView;
    }

    /**
     * 确认身份接口：确定身份以及判断是否二维码过期等
     * @param token
     * @param userId
     * @return
     */
    @RequestMapping(value = "/bindUserIdAndToken" ,method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "确认登陆接口")
    public Object bindUserIdAndToken(@RequestParam("token") String token ,
                                     @RequestParam("userId") Integer userId,
                                     @RequestParam(required = false,value = "projId") Integer projId){

        try {
            return sUserTokenService.bindUserIdAndToken(userId,token,projId);
        } catch (Exception e) {
            e.printStackTrace();
            return "500";
        }

    }
}
